//
//  HMEmoticonKeyboard.swift
//  WeiBo14
//
//  Created by HM on 16/3/12.
//  Copyright © 2016年 HM. All rights reserved.
//  表情键盘

import UIKit

class HMEmoticonKeyboard: UIView {
    
    // 可重用id
    private let HMEmoticonKeyboardCellId = "HMEmoticonKeyboardCellId"

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        backgroundColor = UIColor(patternImage: UIImage(named: "emoticon_keyboard_background")!)
        
        // 添加子控件
        addSubview(toolBar)
        addSubview(collectionView)
        addSubview(pageControl)
        
        // 添加约束
        toolBar.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.bottom.equalTo(self)
        }
        
        collectionView.snp_makeConstraints { (make) -> Void in
            make.leading.top.trailing.equalTo(self)
            make.bottom.equalTo(toolBar.snp_top)
        }
        
        pageControl.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.bottom.equalTo(collectionView)
        }
        
        // 主队列异步
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            // 代表执行到51行,collectionView里面还不知道有多数据
            // 让collectionView滚动到第1组
            let indexPath = NSIndexPath(forItem: 0, inSection: 1)
            self.collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: false)
            // 去选中对应的表情按钮
            self.toolBar.selectedButtonWithSection(indexPath.section)
        }
    }
    
    
    // 通过 indexPath 设置 pageControl当前显示的总页数和当前选中的页
    private func setupPageControl(indexPath: NSIndexPath) {
        pageControl.numberOfPages = HMEmoticonTools.sharedTools.allEmoticons[indexPath.section].count
        pageControl.currentPage = indexPath.item
        // 当是第0组的时候,就隐藏pageControl
        pageControl.hidden = indexPath.section == 0
    }

    
    // MARK: - 懒加载控件
    
    private lazy var pageControl: UIPageControl = {
        let pageControl = UIPageControl()
        // 关闭用户交互
        pageControl.userInteractionEnabled = false
        // 通过kvc设置图片
        pageControl.setValue(UIImage(named: "compose_keyboard_dot_selected"), forKey: "_currentPageImage")
        pageControl.setValue(UIImage(named: "compose_keyboard_dot_normal"), forKey: "_pageImage")
        //        pageControl.currentPageIndicatorTintColor = UIColor(patternImage: UIImage(named: "compose_keyboard_dot_selected")!)
//        pageControl.pageIndicatorTintColor =  UIColor(patternImage: UIImage(named: "compose_keyboard_dot_normal")!)
        return pageControl
    }()
    
    /// 显示表情的View
    private lazy var collectionView: HMEmoticonCollectionView = {
        let collectionView = HMEmoticonCollectionView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())
        // 设置数据源
        collectionView.dataSource = self
        collectionView.delegate = self
        // 注册cell
        collectionView.registerClass(HMEmoticonPageCell.self, forCellWithReuseIdentifier: self.HMEmoticonKeyboardCellId)
        return collectionView
    }()
    
    private lazy var toolBar: HMEmoticonToolbar = {
        let toolBar = HMEmoticonToolbar(frame: CGRectZero)
        toolBar.delegate = self
        return toolBar
    }()
}


// MARK: - collectionView数据源与代理方法
extension HMEmoticonKeyboard: UICollectionViewDataSource, UICollectionViewDelegate {
    
    // 返回有多少组表情
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return HMEmoticonTools.sharedTools.allEmoticons.count
    }
    
    // 返回每一个组表情有多少页
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return HMEmoticonTools.sharedTools.allEmoticons[section].count
    }
    
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        // 从缓存里面取cell
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(HMEmoticonKeyboardCellId, forIndexPath: indexPath) as! HMEmoticonPageCell
        cell.indexPath = indexPath
        
        // 设置表情数据
        cell.emoticons = HMEmoticonTools.sharedTools.allEmoticons[indexPath.section][indexPath.row]
        
        return cell
    }
    
    
    // 监听 collectionView的滚动
    func scrollViewDidScroll(scrollView: UIScrollView) {
        //print(scrollView.contentOffset.x)
        
        // 1. 取到当前collectionView里面可见的两个cell
        let cells = collectionView.visibleCells()
        
        // 2. 查看哪个cell在界面上显示的范围大
        
        if cells.count == 2 {
            // 取到两个cell
            let firstCell = cells.first!
            let lastCell = cells.last!
            
            // 判断这两个cell哪一个在界面上显示得多
            //print("\(firstCell.frame.origin.x),\(lastCell.frame.origin.x)")
            let firstResult = abs(firstCell.frame.origin.x - collectionView.contentOffset.x)
            let lastReulst = abs(lastCell.frame.origin.x - collectionView.contentOffset.x)
            
            //            if firstResult < lastReulst {
            //                print("firstCell显示得多")
            //            }else{
            //                print("lastCell显示得多")
            //            }
            // 取到显示范围大的cell
            let cell = firstResult < lastReulst ? firstCell : lastCell
            // 取到该cell对应的indexPath
            let indexPath = collectionView.indexPathForCell(cell)!
            print("当前显示cell的section:\(indexPath.section)")
            
            // 去选中对应的表情按钮
            toolBar.selectedButtonWithSection(indexPath.section)
            
            setupPageControl(indexPath)
        }
    }
}

// MARK: - 表情类型切换代理方法
extension HMEmoticonKeyboard: HMEmoticonToolbarDelegate {
    
    func emoticonToolar(toolBar: HMEmoticonToolbar, type: HMEmotionType) {
        print(type)
        // 将collectionView滚动到指定的组就可以了
        let indexPath = NSIndexPath(forItem: 0, inSection: type.rawValue)
        // 让collectionView滚动到指定的indexPath
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: false)
        
        setupPageControl(indexPath)
    }
}
